<template>
  <view class="login-container">
    <view class="login-form">
      <view class="logo-section">
        <image class="logo" src="/static/home/Logo.jpg"></image>
        <text class="app-name">ShapeUp 健身</text>
        <text class="app-slogan">让健身更简单</text>
      </view>

      <view class="form-container">
        <view class="form-item">
          <input 
            class="form-input" 
            v-model="formData.username" 
            placeholder="请输入用户名" 
            @focus="clearError('username')"
            :class="{ 'error': errors.username }"
          />
          <text v-if="errors.username" class="error-msg">{{ errors.username }}</text>
        </view>

        <view class="form-item">
          <input 
            class="form-input" 
            v-model="formData.password" 
            password="true" 
            placeholder="请输入密码" 
            @focus="clearError('password')"
            :class="{ 'error': errors.password }"
          />
          <text v-if="errors.password" class="error-msg">{{ errors.password }}</text>
        </view>
      </view>

      <view 
        class="custom-button primary" 
        :class="{ loading: loading }"
        @click="handleLogin"
      >
        <text v-if="!loading">登录</text>
        <text v-else>登录中...</text>
      </view>

      <view class="form-footer">
        <text @click="goToRegister">还没有账号？立即注册</text>
      </view>
      
      <view class="divider">
        <text class="divider-text">其他登录方式</text>
      </view>
      
      <view class="social-login">
        <view class="social-item" @click="socialLogin('wechat')">
          <image class="icon" src="/static/home/wx.png" mode="aspectFit"></image>
          <text class="social-label">微信登录</text>
        </view>
        <view class="social-item" @click="socialLogin('qq')">
          <image class="icon" src="/static/home/qq.png" mode="aspectFit"></image>
          <text class="social-label">QQ登录</text>
        </view>
      </view>
    </view>
    
    <view class="footer-links">
      <text class="link" @click="forgotPassword">忘记密码</text>
      <text class="link">|</text>
      <text class="link" @click="contactSupport">联系客服</text>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { authApi } from '../../src/services/api'

// 加载状态
const loading = ref(false)

// 表单数据
const formData = reactive({
  username: '',
  password: ''
})

// 错误信息
const errors = reactive({
  username: '',
  password: ''
})

// 清除错误信息
const clearError = (field: keyof typeof errors) => {
  errors[field] = ''
}

// 表单验证
const validateForm = () => {
  // 清除之前的错误信息
  errors.username = ''
  errors.password = ''
  
  let isValid = true

  if (!formData.username) {
    errors.username = '请输入用户名'
    isValid = false
  }

  if (!formData.password) {
    errors.password = '请输入密码'
    isValid = false
  } else if (formData.password.length < 6) {
    errors.password = '密码长度不能少于6位'
    isValid = false
  }

  return isValid
}

// 处理登录
const handleLogin = async () => {
  try {
    // 表单验证
    if (!validateForm()) {
      return
    }

    // 设置加载状态
    loading.value = true

    // 执行登录
    const response: any = await authApi.login({
      username: formData.username,
      password: formData.password
    })

    // 将令牌存储到本地
    uni.setStorageSync('token', response.data.accessToken)
    uni.setStorageSync('user', response.data.user)

    // 显示成功消息
    uni.showToast({
      title: '登录成功',
      icon: 'success'
    })

    // 登录成功后跳转到首页
    console.log('Login successful, preparing to navigate to index page')
    setTimeout(() => {
      console.log('Attempting to switch to tab: /pages/index/index')
      uni.switchTab({
        url: '/pages/index/index',
        success: function() {
          console.log('Successfully switched to index tab')
        },
        fail: function(err) {
          console.error('Failed to switch to index tab:', err)
          uni.showToast({
            title: '跳转失败，请重试',
            icon: 'none'
          })
        }
      })
    }, 1500)
  } catch (error: any) {
    console.error('Login error:', error)
    uni.showToast({
      title: error.message || '登录失败',
      icon: 'none'
    })
  } finally {
    // 取消加载状态
    loading.value = false
  }
}

// 社交登录
const socialLogin = (platform: string) => {
  uni.showToast({
    title: `正在跳转到${platform === 'wechat' ? '微信' : 'QQ'}登录`,
    icon: 'none'
  })
  // 这里应该实现具体的社交登录逻辑
  console.log(`Social login with ${platform}`)
}

// 忘记密码
const forgotPassword = () => {
  uni.showToast({
    title: '忘记密码功能开发中',
    icon: 'none'
  })
}

// 联系客服
const contactSupport = () => {
  uni.showToast({
    title: '联系客服功能开发中',
    icon: 'none'
  })
}

// 跳转到注册页面
const goToRegister = () => {
  uni.navigateTo({
    url: '/pages/auth/register'
  })
}
</script>

<style lang="scss">
page {
  height: 100%;
  overflow: hidden;
}
</style>

<style lang="scss" scoped>
.login-container {
  height: 100vh;
  overflow: hidden;
  background-color: #ffffff;
  padding: 20rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  
  .login-form {
    background-color: #fff;
    border-radius: 20rpx;
    padding: 40rpx 40rpx;
    margin: 20rpx;
    box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.2);
    
    .logo-section {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-bottom: 30rpx;
      
      .logo {
        width: 280rpx;
        height: 200rpx;
        border-radius: 20rpx;
        margin-bottom: 20rpx;
        box-shadow: 0 5rpx 15rpx rgba(0, 0, 0, 0.1);
        object-fit: cover;
      }
      
      .app-name {
        font-size: 40rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 10rpx;
      }
      
      .app-slogan {
        font-size: 28rpx;
        color: #999;
      }
    }
    
    .form-container {
      .form-item {
        margin-bottom: 20rpx;
        
        .form-label {
          display: block;
          margin-bottom: 10rpx;
          font-size: 28rpx;
          color: #333;
        }
        
        .form-input {
          width: 100%;
          height: 80rpx;
          padding: 0 20rpx;
          border: 2rpx solid #e5e5e5;
          border-radius: 10rpx;
          font-size: 28rpx;
          box-sizing: border-box;
          transition: border-color 0.3s;
          
          &:focus {
            border-color: #4B0082;
          }
          
          &.error {
            border-color: #ff3b30;
          }
        }
        
        .error-msg {
          color: #ff3b30;
          font-size: 24rpx;
          margin-top: 10rpx;
          display: block;
        }
      }
    }
    
    .custom-button {
      margin-top: 20rpx;
      height: 80rpx;
      font-size: 32rpx;
      border-radius: 40rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      transition: all 0.3s;
      
      &.primary {
        background: linear-gradient(135deg, #4B0082, #8A2BE2);
        color: #fff;
        box-shadow: 0 5rpx 15rpx rgba(75, 0, 130, 0.3);
      }
      
      &.loading {
        opacity: 0.7;
      }
      
      &:active {
        transform: scale(0.98);
      }
    }
    
    .form-footer {
      display: flex;
      justify-content: center;
      margin-top: 30rpx;
      
      text {
        color: #4B0082;
        font-size: 28rpx;
        
        &:active {
          opacity: 0.8;
        }
      }
    }
    
    .divider {
      display: flex;
      align-items: center;
      margin: 30rpx 0 20rpx;

      &::before,
      &::after {
        content: '';
        flex: 1;
        height: 1rpx;
        background-color: #e5e5e5;
      }

      .divider-text {
        font-size: 24rpx;
        color: #999;
        padding: 0 20rpx;
        white-space: nowrap;
      }
    }
    
    .social-login {
      display: flex;
      justify-content: space-around;
      
      .social-item {
        display: flex;
        flex-direction: column;
        align-items: center;

        .icon {
          width: 60rpx;
          height: 60rpx;
          margin-bottom: 10rpx;
        }

        .social-label {
          font-size: 24rpx;
          color: #666;
        }

        &:active {
          opacity: 0.8;
        }
      }
    }
  }
  
  .footer-links {
    display: flex;
    justify-content: center;
    margin-top: 30rpx;
    
    .link {
      color: #4B0082;
      font-size: 24rpx;
      margin: 0 10rpx;
      
      &:active {
        opacity: 0.8;
      }
    }
  }
}
</style>